import time
import uiautomator2 as u2
import cv2
import numpy as np
import pyautogui

# 通过 USB 连接
d = u2.connect()  # 自动连接已连接的设备
info = d.info
width = info['displayWidth']
height = info['displayHeight']

def simulate_click(x, y):
    """
    在指定坐标 (x, y) 处模拟点击事件
    """
    d.click(x, y)
    print(f"已点击坐标: ({x}, {y})")

def simulate_joystick_drag(start_x, start_y, end_x, end_y, steps=10, hold_time=2.0):
    """
    更真实地模拟摇杆拖动：按下->分步移动->抬起
    """
    d.touch.down(start_x, start_y)
    print(f"摇杆按下: ({start_x}, {start_y})")
    for i in range(1, steps + 1):
        x = start_x + (end_x - start_x) * i // steps
        y = start_y + (end_y - start_y) * i // steps
        d.touch.move(x, y)
        time.sleep(0.01)  # 每步间隔，可调整
    print(f"摇杆拖到终点: ({end_x}, {end_y})，停留 {hold_time} 秒")
    time.sleep(hold_time)
    d.touch.up(end_x, end_y)
    print("摇杆抬起")

# 示例：假设摇杆在屏幕左下角，模拟向右上拖动
# joystick_center_x = int(width * 0.5)
# joystick_center_y = int(height * 0.8)
# swipe_end_x = joystick_center_x + 400
# swipe_end_y = joystick_center_y - 400

# simulate_joystick_drag(joystick_center_x, joystick_center_y, swipe_end_x, swipe_end_y, steps=5, hold_time=2.0)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
while True:
    cv_img =  d.screenshot(format="opencv")  # 获取当前屏幕图像
    cv_img = cv2.resize(cv_img, (0, 0), fx=0.3, fy=0.3) # 缩小显示
    cv_img = cv_img[:, :, 1] # 只保留绿色通道
    cv_img = cv2.inRange(cv_img, 155, 165) # 二值化处理
    cv_img = cv2.morphologyEx(cv_img, cv2.MORPH_OPEN, kernel)
    h, w = cv_img.shape[:2]          # 当前图像高、宽
    side = 30                        # 方框边长（像素），可调
    x1 = w // 2 - side // 2          # 左上角 x
    y1 = h // 2+40 - side // 2          # 左上角 y
    x2 = x1 + side                   # 右下角 x
    y2 = y1 + side                   # 右下角 y
    # 画绿色方框，线宽 2 像素
    cv2.rectangle(cv_img, (x1, y1), (x2, y2), 0, 2)

    cv2.imshow("Phone Screen", cv_img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
